package com.yc.sole.erp.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;
import com.yc.sole.common.constant.PubConstant;
import com.yc.sole.common.domain.StateCountResp;
import com.yc.sole.erp.dto.*;
import com.yc.sole.erp.enums.*;
import com.yc.sole.erp.excel.OrderExcel;
import com.yc.sole.erp.exception.ErpResultEnum;
import com.yc.sole.erp.repository.*;
import com.yc.sole.erp.request.SaleOrderItemReq;
import com.yc.sole.erp.request.SaleOrderQueryReq;
import com.yc.sole.erp.request.SaleOrderReq;
import com.yc.sole.erp.request.SaleOrderSaveReq;
import com.yc.sole.erp.response.*;
import com.yc.sole.framework.exception.BaseException;
import com.yc.sole.framework.mybatis.page.Paging;
import com.yc.sole.framework.mybatis.util.PageUtil;
import com.yc.sole.framework.utils.EasyExcelUtil;
import com.yc.sole.system.dto.ConfigDto;
import com.yc.sole.system.repository.ConfigRepository;
import com.yc.sole.system.service.SequenceService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务接口实现
 *
 * @author yizuomin
 * @date 2023-12-15
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class SaleOrderBiz {

    private final SaleOrderRepository saleOrderRepository;
    private final CustomerRepository customerRepository;
    private final ProductRepository productRepository;
    private final CategoryRepository categoryRepository;
    private final ProduceRepository produceRepository;
    private final SequenceService sequenceService;
    private final ConfigRepository configRepository;
    private final BomRepository bomRepository;
    private final MaterialRepository materialRepository;
    private final OsOrderRepository osOrderRepository;
    private final MoldRepository moldRepository;

    /**
     * 新增
     *
     * @param req
     */
    @Transactional(rollbackFor = Exception.class)
    public List<Long> saveSaleOrder(SaleOrderSaveReq req) {
        // 查询客户
        CustomerDto customerDto = customerRepository.selectCustomerById(req.getCustomerId());
        if (Objects.isNull(customerDto)) {
            throw new BaseException(ErpResultEnum.CUSTOMER_NOT_FOUND);
        }
        Set<Long> moldIds = req.getItemList().stream().map(SaleOrderItemReq::getMoldId).collect(Collectors.toSet());
        Map<Long, MoldDto> moldDtoMap = moldRepository.selectMoldByIds(moldIds).stream().collect(Collectors.toMap(MoldDto::getId, v -> v));
        Set<SaleOrderDto> saleOrderDtoList = req.getItemList().stream().map(e -> {
            MoldDto moldDto = moldDtoMap.get(e.getMoldId());
            // 查询是否存在产品信息，不存在则新增
            ProductDto productDto = productRepository.selectByIdDetail(moldDto.getId(), e.getColor(), e.getMaterial(), e.getSize(), e.getLength());
            if (Objects.isNull(productDto)) {
                productDto = productRepository.saveAndReturn(moldDto, e.getColor(), e.getMaterial(), e.getSize(), e.getLength());
            }
            // 生成订单号
            String orderNo = sequenceService.generateSeqNo(PubConstant.SALE_ORDER_SEQ_KEY);
            SaleOrderDto saleOrderDto = new SaleOrderDto();
            saleOrderDto.setOrderNo(orderNo);
            saleOrderDto.setOrderDate(req.getOrderDate());
            saleOrderDto.setCustomerId(customerDto.getId());
            saleOrderDto.setCustomerName(customerDto.getCustomerName());
            saleOrderDto.setProductId(productDto.getId());
            saleOrderDto.setProductName(productDto.getProductName());
            saleOrderDto.setUnitPrice(e.getUnitPrice());
            saleOrderDto.setQuantity(e.getQuantity());
            saleOrderDto.setUnit(productDto.getUnit());
            // 计算金额
            saleOrderDto.setAmount(e.getUnitPrice().multiply(BigDecimal.valueOf(e.getQuantity())));
            saleOrderDto.setRemark(e.getRemark());
            saleOrderDto.setPriority(req.getPriority());
            saleOrderDto.setOrderState(OrderState.UN_HANDLE);
            saleOrderDto.setPaymentState(PaymentState.PENDING);
            saleOrderDto.setPaidAmount(BigDecimal.ZERO);
            saleOrderDto.setShippedQuantity(0);
            saleOrderDto.setShipmentState(ShipmentState.UN_SHIPPED);
            return saleOrderDto;
        }).collect(Collectors.toSet());
        return saleOrderRepository.saveSaleOrder(saleOrderDtoList);
    }

    /**
     * 修改
     *
     * @param saleOrderReq
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateSaleOrderById(SaleOrderReq saleOrderReq) {
        SaleOrderDto saleOrderDto = saleOrderRepository.selectSaleOrderById(saleOrderReq.getId());
        if (Objects.isNull(saleOrderDto)) {
            throw new BaseException(ErpResultEnum.SALE_ORDER_NOT_FOUND);
        }
        if (!OrderState.UN_HANDLE.equals(saleOrderDto.getOrderState()) && !OrderState.PROCESSING.equals(saleOrderDto.getOrderState())) {
            throw new BaseException(ErpResultEnum.ORDER_CAN_NOT_UPDATE, saleOrderDto.getOrderState().getDescription());
        }
        // 查询模具
        MoldDto moldDto = moldRepository.selectMoldById(saleOrderReq.getMoldId());
        if (Objects.isNull(moldDto)) {
            throw new BaseException(ErpResultEnum.MOLD_NOT_FOUND);
        }
        // 查询客户
        CustomerDto customerDto = customerRepository.selectCustomerById(saleOrderDto.getCustomerId());
        if (Objects.isNull(customerDto)) {
            throw new BaseException(ErpResultEnum.CUSTOMER_NOT_FOUND);
        }
        // 查询是否存在产品信息，不存在则新增
        ProductDto productDto = productRepository.selectByIdDetail(moldDto.getId(), saleOrderReq.getColor(), saleOrderReq.getMaterial(), saleOrderReq.getSize(), saleOrderReq.getLength());
        if (Objects.isNull(productDto)) {
            productDto = productRepository.saveAndReturn(moldDto, saleOrderReq.getColor(), saleOrderReq.getMaterial(), saleOrderReq.getSize(), saleOrderReq.getLength());
        }
        SaleOrderDto dto = new SaleOrderDto();
        dto.setId(saleOrderReq.getId());
        dto.setOrderDate(saleOrderReq.getOrderDate());
        dto.setCustomerId(saleOrderReq.getCustomerId());
        dto.setProductId(productDto.getId());
        dto.setProductName(productDto.getProductName());
        dto.setUnitPrice(saleOrderReq.getUnitPrice());
        dto.setQuantity(saleOrderReq.getQuantity());
        dto.setUnit(productDto.getUnit());
        // 计算金额
        dto.setAmount(saleOrderReq.getUnitPrice().multiply(BigDecimal.valueOf(saleOrderReq.getQuantity())));
        dto.setRemark(saleOrderReq.getRemark());
        dto.setPriority(saleOrderReq.getPriority());
        // 修改订单
        saleOrderRepository.updateSaleOrderById(dto);
        // 修改生产信息
        ProduceDto produceDto = produceRepository.selectByOrderId(saleOrderDto.getId());
        if (Objects.isNull(produceDto)) {
            return;
        }
        // 判断数量是否正确
        int quantity = produceDto.getQuantity() - produceDto.getRemainingQuantity();
        if (quantity > saleOrderReq.getQuantity()) {
            throw new BaseException(ErpResultEnum.ORDER_QUANTITY_ERROR_CAN_NOT_UPDATE, quantity, dto.getQuantity());
        }
        ProduceDto updateProduceDto = new ProduceDto();
        updateProduceDto.setId(produceDto.getId());
        updateProduceDto.setProductId(dto.getProductId());
        updateProduceDto.setProductName(dto.getProductName());
        updateProduceDto.setCustomerId(dto.getCustomerId());
        updateProduceDto.setCustomerName(dto.getCustomerName());
        updateProduceDto.setQuantity(dto.getQuantity());
        updateProduceDto.setRemainingQuantity(dto.getQuantity() - quantity);
        updateProduceDto.setPriority(dto.getPriority());
        updateProduceDto.setRemark(dto.getRemark());
        if (updateProduceDto.getRemainingQuantity() == 0) {
            updateProduceDto.setProduceState(ProduceState.FINISHED);
        }
        produceRepository.updateProduceById(updateProduceDto);
    }

    /**
     * 取消订单
     *
     * @param orderId
     */
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(Long orderId) {
        SaleOrderDto saleOrderDto = saleOrderRepository.selectSaleOrderById(orderId);
        if (Objects.isNull(saleOrderDto)) {
            throw new BaseException(ErpResultEnum.SALE_ORDER_NOT_FOUND);
        }
        if (OrderState.COMPLETED.equals(saleOrderDto.getOrderState())
                || OrderState.CANCELED.equals(saleOrderDto.getOrderState())) {
            throw new BaseException(ErpResultEnum.ORDER_CAN_NOT_CANCEL, saleOrderDto.getOrderState().getDescription());
        }
        SaleOrderDto updateDto = new SaleOrderDto();
        updateDto.setId(orderId);
        updateDto.setOrderState(OrderState.CANCELED);
        updateDto.setPriority(PriorityType.NORMAL);
        saleOrderRepository.updateSaleOrderById(updateDto);
        if (!OrderState.UN_HANDLE.equals(saleOrderDto.getOrderState())) {
            // 查询生产单
            ProduceDto produceDto = produceRepository.selectByOrderId(orderId);
            // 修改生产为已取消
            if (Objects.nonNull(produceDto)) {
                produceRepository.updateProduceState(produceDto.getId(), ProduceState.CANCEL);
            }
            // 查询外发订单，修改外发订单为已取消
            OsOrderDto osOrderDto = osOrderRepository.selectByOrderId(orderId);
            if (Objects.nonNull(osOrderDto)) {
                OsOrderDto updateOsDto = new OsOrderDto();
                updateOsDto.setId(osOrderDto.getId());
                osOrderRepository.updateOsOrderById(updateOsDto);
            }
        }
    }

    /**
     * 根据订单id查询订单详情
     *
     * @param orderId
     * @return
     */
    public SaleOrderResp selectSaleOrderById(Long orderId) {
        SaleOrderDto saleOrderDto = saleOrderRepository.selectSaleOrderById(orderId);
        if (Objects.isNull(saleOrderDto)) {
            return null;
        }
        SaleOrderResp saleOrderResp = BeanUtil.copyProperties(saleOrderDto, SaleOrderResp.class);
        ProductDto productDto = productRepository.selectProductById(saleOrderDto.getProductId());
        if (Objects.nonNull(productDto)) {
            saleOrderResp.setProductInfo(BeanUtil.copyProperties(productDto, ProductResp.class));
        }
        CustomerDto customerDto = customerRepository.selectCustomerById(saleOrderDto.getCustomerId());
        if (Objects.nonNull(customerDto)) {
            saleOrderResp.setCustomerName(customerDto.getCustomerName());
        }
        ProduceDto produceDto = produceRepository.selectByOrderId(orderId);
        if (Objects.nonNull(produceDto)) {
            saleOrderResp.setProduceInfo(BeanUtil.copyProperties(produceDto, ProduceResp.class));
        }
        OsOrderDto osOrderDto = osOrderRepository.selectByOrderId(orderId);
        if (Objects.nonNull(osOrderDto)) {
            saleOrderResp.setOutsourcedInfo(BeanUtil.copyProperties(osOrderDto, OsOrderResp.class));
        }
        // 设置税率信息
        computeOrderTax(saleOrderResp);
        return saleOrderResp;
    }

    /**
     * 删除
     *
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteSaleOrder(Collection<Long> ids) {
        List<SaleOrderDto> saleOrderDtos = saleOrderRepository.selectSaleOrderByIds(ids);
        for (SaleOrderDto saleOrderDto : saleOrderDtos) {
            if (!OrderState.UN_HANDLE.equals(saleOrderDto.getOrderState())
                    && !OrderState.CANCELED.equals(saleOrderDto.getOrderState())) {
                throw new BaseException(ErpResultEnum.ORDER_CAN_NOT_DELETE, saleOrderDto.getOrderState().getDescription());
            }
        }
        //删除订单
        saleOrderRepository.deleteSaleOrder(ids);
    }

    /**
     * 分页查询
     *
     * @param page
     * @param saleOrderPageReq
     * @return
     */
    public Paging<SaleOrderResp> selectSaleOrderPage(Paging<SaleOrderQueryReq> page, SaleOrderQueryReq saleOrderPageReq) {
        Paging<SaleOrderDto> paging = saleOrderRepository.selectSaleOrderPage(page, saleOrderPageReq);
        Paging<SaleOrderResp> orderRespPaging = PageUtil.pageCopy(paging, SaleOrderResp.class);
        if (CollUtil.isEmpty(orderRespPaging.getRecords())) {
            return orderRespPaging;
        }
        Set<Long> productIds = orderRespPaging.getRecords().stream().map(SaleOrderResp::getProductId).collect(Collectors.toSet());
        List<ProductDto> productDtoList = productRepository.selectProductByIds(productIds);
        Map<Long, ProductDto> productDtoMap = productDtoList.stream().collect(Collectors.toMap(ProductDto::getId, v -> v));
        for (SaleOrderResp saleOrderResp : orderRespPaging.getRecords()) {
            ProductDto productDto = productDtoMap.get(saleOrderResp.getProductId());
            if (Objects.nonNull(productDto)) {
                saleOrderResp.setProductInfo(BeanUtil.copyProperties(productDto, ProductResp.class));
            }
            computeOrderTax(saleOrderResp);
        }
        return orderRespPaging;
    }

    /**
     * 计算订单税率信息
     *
     * @param saleOrderResp
     */
    private void computeOrderTax(SaleOrderResp saleOrderResp) {
        ConfigDto configDto = configRepository.selectConfig();
        // 税率
        BigDecimal taxRate = new BigDecimal(String.valueOf(configDto.getTaxRate()));
        saleOrderResp.setTaxRate(taxRate);
        // 总金额
        BigDecimal amount = saleOrderResp.getUnitPrice().multiply(BigDecimal.valueOf(saleOrderResp.getQuantity()));
        saleOrderResp.setAmount(amount);
        // 不含税总金额
        BigDecimal tax = saleOrderResp.getAmount().multiply(taxRate).divide(new BigDecimal("100"), RoundingMode.HALF_UP);
        saleOrderResp.setUnTaxAmount(saleOrderResp.getAmount().subtract(tax));
        // 不含税单价
        BigDecimal taxPrice = saleOrderResp.getUnitPrice().multiply(taxRate).divide(new BigDecimal("100"), RoundingMode.HALF_UP);
        saleOrderResp.setUnTaxPrice(saleOrderResp.getUnitPrice().subtract(taxPrice));
    }

    /**
     * 根据订单编号查询订单详情
     *
     * @param orderNo
     * @return
     */
    public List<SaleOrderResp> selectSaleOrderByOrderNoLike(String orderNo) {
        List<SaleOrderDto> saleOrderDtoList = saleOrderRepository.selectSaleOrderByOrderNoLike(orderNo);
        List<SaleOrderResp> saleOrderRespList = BeanUtil.copyToList(saleOrderDtoList, SaleOrderResp.class);
        if (CollUtil.isEmpty(saleOrderRespList)) {
            return saleOrderRespList;
        }
        Set<Long> customerIds = saleOrderRespList.stream().map(SaleOrderResp::getCustomerId).collect(Collectors.toSet());
        Set<Long> productIds = saleOrderRespList.stream().map(SaleOrderResp::getProductId).collect(Collectors.toSet());
        Map<Long, CustomerDto> customerDtoMap = customerRepository.selectCustomerByIds(customerIds).stream().collect(Collectors.toMap(CustomerDto::getId, v -> v));
        Map<Long, ProductDto> productDtoMap = productRepository.selectProductByIds(productIds).stream().collect(Collectors.toMap(ProductDto::getId, v -> v));
        for (SaleOrderResp saleOrderResp : saleOrderRespList) {
            CustomerDto customerDto = customerDtoMap.get(saleOrderResp.getCustomerId());
            if (Objects.nonNull(customerDto)) {
                saleOrderResp.setCustomerName(customerDto.getCustomerName());
            }
            ProductDto productDto = productDtoMap.get(saleOrderResp.getProductId());
            if (Objects.nonNull(productDto)) {
                saleOrderResp.setProductName(productDto.getProductName());
            }
        }
        return saleOrderRespList;
    }

    /**
     * 利润计算
     *
     * @param orderId
     * @return
     */
    public List<SaleOrderBomResp> profitCalculation(Long orderId) {
        SaleOrderDto saleOrderDto = saleOrderRepository.selectSaleOrderById(orderId);
        List<BomDto> bomDtoList = bomRepository.selectBomByProductIds(Lists.newArrayList(saleOrderDto.getProductId()));
        Set<Long> materialIds = bomDtoList.stream().map(BomDto::getMaterialId).collect(Collectors.toSet());
        Map<Long, MaterialDto> materialDtoMap = materialRepository.selectMaterialByIds(materialIds).stream().collect(Collectors.toMap(MaterialDto::getId, v -> v));

        // 产品
        ProductDto productDto = productRepository.selectProductById(saleOrderDto.getProductId());
        // bom
        SaleOrderBomResp saleOrderBomResp = new SaleOrderBomResp();
        saleOrderBomResp.setProductName(productDto.getProductName());
        saleOrderBomResp.setQuantity(saleOrderDto.getQuantity());
        saleOrderBomResp.setUnitPrice(saleOrderDto.getUnitPrice());
        saleOrderBomResp.setAmount(saleOrderDto.getAmount());
        List<SaleOrderBomResp.SaleOrderBomDetailResp> itemBomResps = bomDtoList.stream().map(bomDto -> {
            MaterialDto materialDto = materialDtoMap.get(bomDto.getMaterialId());
            SaleOrderBomResp.SaleOrderBomDetailResp saleOrderItemBomResp = new SaleOrderBomResp.SaleOrderBomDetailResp();
            saleOrderItemBomResp.setMaterialName(materialDto.getName());
            saleOrderItemBomResp.setUnit(bomDto.getUnit());
            saleOrderItemBomResp.setQuantity(bomDto.getQuantity());
            saleOrderItemBomResp.setTotalQuantity(bomDto.getQuantity() * saleOrderDto.getQuantity() * 2);
            saleOrderItemBomResp.setUnitPrice(materialDto.getUnitPrice());
            BigDecimal productQuantity = new BigDecimal(String.valueOf(saleOrderDto.getQuantity()));
            BigDecimal bomQuantity = new BigDecimal(String.valueOf(bomDto.getQuantity() * 2));
            BigDecimal cost = bomQuantity.multiply(materialDto.getUnitPrice()).multiply(productQuantity).setScale(2, RoundingMode.HALF_UP);
            saleOrderItemBomResp.setMaterialCost(cost);
            return saleOrderItemBomResp;
        }).toList();
        saleOrderBomResp.setDetailBomList(itemBomResps);

        BigDecimal totalCost = itemBomResps.stream().map(SaleOrderBomResp.SaleOrderBomDetailResp::getMaterialCost).reduce(BigDecimal.ZERO, BigDecimal::add);
        saleOrderBomResp.setMaterialCost(totalCost);
        saleOrderBomResp.setProfit(saleOrderBomResp.getAmount().subtract(totalCost));
        return Lists.newArrayList(saleOrderBomResp);
    }

    /**
     * 导出订单
     *
     * @param saleOrderQueryReq
     * @param response
     */
    public void export(SaleOrderQueryReq saleOrderQueryReq, HttpServletResponse response) {
        List<SaleOrderDto> saleOrderDtoList = saleOrderRepository.selectSaleOrderList(saleOrderQueryReq);
        List<OrderExcel> orderExcelList = new ArrayList<>();
        /*if (CollUtil.isNotEmpty(saleOrderDtoList)) {
            Set<Long> customerIds = saleOrderDtoList.stream().map(SaleOrderDto::getCustomerId).collect(Collectors.toSet());
            Map<Long, CustomerDto> customerDtoMap = customerRepository.selectCustomerByIds(customerIds).stream().collect(Collectors.toMap(CustomerDto::getId, v -> v));
            Set<Long> productIds = saleOrderDtoList.stream().map(SaleOrderDto::getProductId).collect(Collectors.toSet());
            List<ProductDto> productDtos = productRepository.selectProductByIds(productIds);
            Map<Long, ProductDto> productDtoMap = productDtos.stream().collect(Collectors.toMap(ProductDto::getId, v -> v));
            Set<Long> categoryIds = productDtos.stream().map(ProductDto::getCategoryId).collect(Collectors.toSet());
            Map<Long, CategoryDto> categoryDtoMap = categoryRepository.selectCategoryByIds(categoryIds).stream().collect(Collectors.toMap(CategoryDto::getId, v -> v));
            ConfigDto configDto = configRepository.selectConfig();
            // 设置不含税总金额
            BigDecimal taxRate = new BigDecimal(String.valueOf(configDto.getTaxRate()));
            orderExcelList = saleOrderDtoList.stream().map(orderDto -> {
                OrderExcel orderExcel = new OrderExcel();
                orderExcel.setOrderNo(orderDto.getOrderNo());
                orderExcel.setOrderDate(orderDto.getOrderDate());
                CustomerDto customerDto = customerDtoMap.get(orderDto.getCustomerId());
                if (Objects.nonNull(customerDto)) {
                    orderExcel.setCustomerName(customerDto.getCustomerName());
                }
                orderExcel.setTotalQuantity(orderDto.getQuantity());
                ProductDto productDto = productDtoMap.get(orderDto.getProductId());
                if (Objects.nonNull(productDto)) {
                    orderExcel.setProductName(productDto.getProductName());
                    orderExcel.setUnit(productDto.getUnit());
                }
                CategoryDto categoryDto = categoryDtoMap.get(orderDto.getCategoryId());
                if (Objects.nonNull(categoryDto)) {
                    orderExcel.setCategoryName(categoryDto.getCategoryName());
                }
                orderExcel.setColor(orderDto.getColor());
                orderExcel.setMaterial(orderDto.getMaterial());
                orderExcel.setSize(orderDto.getSize());
                orderExcel.setLength(orderDto.getLength());
                orderExcel.setUnitPrice(orderDto.getUnitPrice());
                BigDecimal unitPriceTax = orderDto.getUnitPrice().multiply(taxRate).divide(new BigDecimal("100"), RoundingMode.HALF_UP);
                orderExcel.setUnTaxPrice(orderDto.getUnitPrice().subtract(unitPriceTax));
                orderExcel.setQuantity(orderDto.getQuantity());
                orderExcel.setAmount(orderDto.getAmount());
                BigDecimal amountTax = orderDto.getAmount().multiply(taxRate).divide(new BigDecimal("100"), RoundingMode.HALF_UP);
                BigDecimal unTaxAmount = orderDto.getAmount().subtract(amountTax);
                orderExcel.setUnTaxAmount(unTaxAmount);
                return orderExcel;
            }).toList();
        }*/
        EasyExcelUtil.exportExcel(response, orderExcelList, "", "Sheet1", new int[]{0, 1, 2, 3, 4, 5}, 1);
    }

    /**
     * 查询订单状态的数量
     *
     * @return
     */
    public List<StateCountResp> selectOrderStateCount(SaleOrderQueryReq queryReq) {
        List<StateCountResp> countRespList = saleOrderRepository.selectOrderStateCount(queryReq);
        Long totalCount = countRespList.stream().map(StateCountResp::getCount).reduce(0L, Long::sum);
        ArrayList<StateCountResp> resultList = Lists.newArrayList(new StateCountResp("-1", "全部", totalCount));
        Map<String, StateCountResp> stateCountRespMap = countRespList.stream().collect(Collectors.toMap(StateCountResp::getState, v -> v));
        List<StateCountResp> respList = Arrays.stream(OrderState.values()).map(state -> {
            StateCountResp countResp = stateCountRespMap.get(state.getValue());
            if (Objects.isNull(countResp)) {
                countResp = new StateCountResp();
                countResp.setCount(0L);
            }
            countResp.setStateName(state.getDescription());
            countResp.setState(state.getValue());
            return countResp;
        }).toList();
        resultList.addAll(respList);
        return resultList;
    }

    /**
     * 提前终止订单
     *
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    public void termination(Set<Long> ids) {
        List<SaleOrderDto> saleOrderDtoList = saleOrderRepository.selectSaleOrderByIds(ids);
        if (CollUtil.isEmpty(saleOrderDtoList)) {
            throw new BaseException(ErpResultEnum.SALE_ORDER_NOT_FOUND);
        }
        for (SaleOrderDto saleOrderDto : saleOrderDtoList) {
            // 判断状态
            if (!OrderState.PROCESSING.equals(saleOrderDto.getOrderState())) {
                throw new BaseException(ErpResultEnum.ORDER_CAN_NOT_TERMINATION, saleOrderDto.getOrderState().getDescription());
            }
            SaleOrderDto updateDto = new SaleOrderDto();
            updateDto.setId(saleOrderDto.getId());
            updateDto.setOrderState(OrderState.COMPLETED);
            updateDto.setRemark(saleOrderDto.getRemark() + "（订单提前终止）");
            saleOrderRepository.updateSaleOrderById(updateDto);
            // 修改排产为已结束
            ProduceDto produceDto = produceRepository.selectByOrderId(saleOrderDto.getId());
            if (Objects.nonNull(produceDto)) {
                ProduceDto updateProduceDto = new ProduceDto();
                updateProduceDto.setId(produceDto.getId());
                updateProduceDto.setProduceState(ProduceState.FINISHED);
                updateProduceDto.setRemark(produceDto.getRemark() + "（订单提前终止）");
                produceRepository.updateProduceById(updateProduceDto);
            }
        }
    }
}
